# coding=utf-8

import logging
import os
from sys import stdout

import pexpect
from pexpect import run


class AfterImport(object):

    def get_local_ip(self):
        sh = '/bin/bash -c ' \
             '"/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk \'{print $2}\'|tr -d \"addr:\""'
        print('start execute shell : %s', sh)
        output, status = pexpect.run(sh, withexitstatus=1, timeout=30)
        print('=======> shell status: %s, local_ip: %s', status, output)
        if status == 0:
            return str(output).strip().replace('\r\n','')
        else:
            raise RuntimeError('Get local IP address failed')

    def __replace_keyword__(self, params, temp_path, filename):
        if os.path.isfile(filename):
            print('=====> start replace and copy import after sql file[%s]', filename)
            db_name = params['db_name']
            local_ip = params['local_ip']
            print('=====> local ipaddress: [%s]', local_ip)
            new_filename = temp_path + '/' + os.path.basename(filename)
            tbs = open(filename)
            lines = tbs.readlines()
            fp = open(new_filename, 'w')
            for line in lines:
                if line.find('${dbname}') >= 0:
                    line = line.replace('${dbname}', db_name)
                if line.find('$localIp') >= 0:
                    line = line.replace('$localIp', local_ip)
                fp.write(line)
            fp.close()
            tbs.close()
            print('=====> end replace and copy import after sql file')

            print('=======> Start read&write permissions to the script')
            sh = '/bin/bash -c "chmod 777 %s"' % new_filename
            print('=======> execute shell : %s', sh)
            run(sh, withexitstatus=1, logfile=stdout)

            return new_filename
        else:
            return None

    def __do_oracle_execute__(self, params={'after_imp_sql_files': None}):
        print('********************************************************')
        print("=======> AfterImportTask:Entered execute()")

        try:
            temp_path = '%s/%s/afterimp' % (params['temp_path'], params['db_name'])
            sh = 'mkdir -p %s' % temp_path
            print('start execute shell : %s', sh)
            output, status = pexpect.run(sh, withexitstatus=1, timeout=30, logfile=stdout)
            print('=======> shell status: %s, output: %s', status, output)

            if 'after_imp_sql_files' in params.keys():
                sqls = params['after_imp_sql_files']
                if len(sqls) > 0:

                    for sql in sqls:
                        sql_file = self.__replace_keyword__(params, temp_path, sql)
                        if sql_file:
                            sqlplus = pexpect.spawn('su - oracle', timeout=10)
                            sqlplus.logfile = stdout
                            sqlplus.expect('$')
                            sqlplus.sendline('sqlplus %s/%s' % (params['username'], params['password']))
                            sqlplus.expect('SQL>')
                            print('=====> Start executing SQL script file: %s', sql_file)
                            sqlplus.sendline('@%s;' % sql_file)
                            index = sqlplus.expect(['Disconnected from Oracle Database', pexpect.EOF], timeout=None)
                            if index == 0:
                                print('execute SQL script success')
                            elif index == 1:
                                print('execute SQL failure : %s.' % sql_file)

                            sqlplus.sendcontrol('d')
                            sqlplus.close()
                else:
                    print('=======> There is no need to execute the SQL script file')
            else:
                print('=======> There is no need to execute the SQL script file')

        except BaseException, e:
            print('=======> ' + e.message)

        print("=======> AfterImportTask:Exit execute()")

    def __do_cassandra_execute__(self, params={}):
        print('********************************************************')
        print("=======> CassandraAfterImportTask:Entered execute()")

        cassandra_home = params['cassandra_path']
        username = params['username']
        password = params['password']
        keyspace = params['keyspace']
        print('=======> start cassandra after import : %s', keyspace)
        try:
            temp_path = '%s/%s/afterimp' % (params['temp_path'], keyspace)
            sh = 'mkdir -p %s' % temp_path
            print('start execute shell : %s', sh)
            output, status = pexpect.run(sh, withexitstatus=1, timeout=30, logfile=stdout)
            print('=======> shell status: %s, output: %s', status, output)
            if status != 0:
                print('create dir[%s] failure, cause: %s.' % (temp_path, output))

            if 'after_imp_sql_files' in params.keys():
                after_imp_sql_files = params['after_imp_sql_files']
                if after_imp_sql_files and len(after_imp_sql_files) > 0:
                    for sql_file in after_imp_sql_files:
                        sql_file = self.__replace_keyword__(params, temp_path, sql_file)
                        if sql_file:
                            sh = '/bin/bash -c "%s/bin/cqlsh -u %s -p%s --no-color -k %s < %s"' \
                                 % (cassandra_home, username, password, keyspace, sql_file)
                            print('start execute shell : %s', sh)

                            output, status = run(sh, withexitstatus=1, timeout=300, logfile=stdout)
                            print('=======> shell status: %s, output: %s', status, output)

                            if status == 0:
                                print('=======> cassandra after import success')
                            else:
                                print('=======> cassandra after import failure, cause: %s.', output)
                        else:
                            print('=======> after the introduction of the import of the script does not exist')
            else:
                print('=======> after the introduction of the import of the script does not exist')

        except Exception, e:
            print('=======> ' + e.message)
        print("=======> CassandraAfterImportTask:Exit execute()")
        
    def __do_mysql_execute__(self, params={}):
        print('********************************************************')
        print("=======> MysqlAfterImportTask:Entered execute()")

        username = params['username']
        password = params['password']
        db_name = params['db_name']
        print('=======> start mysql data clean : %s', db_name)
        try:
            temp_path = '%s/%s/afterimp' % (params['temp_path'], params['db_name'])
            sh = 'mkdir -p %s' % temp_path
            print('start execute shell : %s', sh)
            output, status = pexpect.run(sh, withexitstatus=1, timeout=30, logfile=stdout)
            print('=======> shell status: %s, output: %s', status, output)
            if status != 0:
                print('create dir[%s] failure, cause: %s.' % (temp_path, output))

            if 'after_imp_sql_files' in params.keys():
                after_imp_sql_files = params['after_imp_sql_files']
                if after_imp_sql_files and len(after_imp_sql_files) > 0:
                    for sql_file in after_imp_sql_files:
                        sql_file = self.__replace_keyword__(params, temp_path, sql_file)
                        if sql_file:
                            sh = '/bin/bash -c "mysql -u%s -p%s %s < %s"' % (username, password, db_name, sql_file)
                            print('start execute shell : %s', sh)
                            output, status = pexpect.run(sh, withexitstatus=1, timeout=3600, logfile=stdout)

                            print('=======> shell status: %s, output: %s', status, output)

                            if status == 0:
                                print('=======> mysql after import success')
                            else:
                                print('mysql after import failure, cause: %s.' % output)
                        else:
                            print('=======> after the introduction of the import of the script does not exist')
            else:
                print('=======> after the introduction of the import of the script does not exist')

        except Exception, e:
            print('=======> ' + e.message)
        print("=======> MysqlAfterImportTask:Exit execute()")

    def execute(self, username, password, db_type):
        filepath = os.getcwd() + '/' + db_type
        filenames = os.listdir(filepath)

        for filename in filenames:
            db_name = filename.split('.')[0]
            local_ip = self.get_local_ip()
            temp_path = '%s/%s/%s' % ('/usr/local/temp', db_type, db_name)
            after_imp_sql_files = []
            after_imp_sql_files.append(filepath + '/' + filename)

            if db_type == 'oracle':
                if db_name == 'ERP':
                    username = 'adempiere'
                else:
                    username = db_name

            params = {'db_name': db_name,
                      'keyspace':db_name,
                      'local_ip': local_ip,
                      'temp_path': temp_path,
                      'username': username,
                      'password': password,
                      'cassandra_path': '/usr/local/db/cassandra',
                      'after_imp_sql_files': after_imp_sql_files}
            if db_type == 'oracle':
                self.__do_oracle_execute__(params=params)
            elif db_type == 'mysql':
                self.__do_mysql_execute__(params=params)
            elif db_type == 'cassandra':
                self.__do_cassandra_execute__(params=params)
            print filename


if __name__ == '__main__':
    a = AfterImport()
    #a.execute('adempiere', 'adempiere', 'oracle')
    a.execute('root', 'winit2015', 'mysql')
    a.execute('cassandra', 'cassandra', 'cassandra')

